package com.jacken.mars.entity.base;


import java.util.concurrent.locks.ReentrantLock;

public class SecurityContextHolder {

    private static ThreadLocal<Authentication> CONTEXT = new ThreadLocal<>();

    private static ReentrantLock lock = new ReentrantLock();

    /**
     * 设置用户信息上下文
     *
     * @param authentication 用户
     */
    public static void setContext(Authentication authentication) {
        CONTEXT.set(authentication);
    }

    /**
     * 获取上下文
     *
     * @return 个人数据
     */
    public static Authentication getContext() {
        Authentication authentication = null;
        if (lock.tryLock()) {
            authentication = CONTEXT.get();
            if (authentication == null) {
                authentication = new Authentication();
                CONTEXT.set(authentication);
            }
            lock.unlock();
        }
        return authentication;
    }

    /**
     * 移除
     */
    public static void clear() {
        CONTEXT.remove();
    }
}
